package com.zhenyi.zhengfang.admin.index;

import com.cjw.model.DBMap;
import com.jfinal.aop.Clear;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.plugin.activerecord.SqlPara;
import com.utils.AESUtils;
import com.utils.AuthUtils;
import com.zhengfang.common.model.ZfAdmin;

import cn.hutool.core.util.RandomUtil;

public class AuthController extends ZFAdminController {

	@Clear
	public void index() {
		String key = RandomUtil.randomString(16);
		setAttr("key", key);
		setSessionAttr("key", key);
		render("/zf/admin/login.html");
	}

	@Clear
	public void login() {
		AuthUtils.logout(this);
		String username = getPara("username");
		String password = getPara("password");
		if (StrKit.isBlank(username)) {
			renderFailure(500, "请输入账号");
			return;
		}
		if (StrKit.isBlank(password)) {
			renderFailure(500, "请输入密码");
			return;
		}
		DBMap map = new DBMap();
		map.put("username", username);
		String key = getSessionAttr("key");
		password = AESUtils.decrypt(key, password);
		map.put("password", password);
		ZfAdmin user = ZfAdmin.dao.searchFirst(map);
		String token = AuthUtils.login(String.valueOf(user.getId()), this);
		if (user == null) {
			renderFailure(500, "账号/密码错误");
			return;
		}
		renderSuccess(user);

	}

	public void list() {
		// List<ZfAdmin> user=ZfAdmin.dao.findAll();
		SqlPara sqlPara = db.getSqlPara("ZfAdminUser");
		Page<Record> pages = db.paginate(getPage(), getPageSize(), sqlPara);
		setRainbow(pages);
		setItems(pages.getList());
		render("/zf/admin/adminuser/list.html");
	}

	public void info() {
		render("/zf/admin/adminuser/info.html");
	}

	public void submit() {
		// Long id = getParaToLong("id");
		String username = getPara("username");
		String password = getPara("password");
		if (StrKit.isBlank(username) || StrKit.isBlank(password)) {
			renderMsg("账号密码不能为空");
			return;
		}
		ZfAdmin info = null;
		ZfAdmin name = ZfAdmin.dao.searchFirst("username", username);
		if (name == null) {
			info = new ZfAdmin();
			info.setUsername(username);
			info.setPassword(password);
			info.save();
		} else {
			// System.out.println("账号已存在");
			renderMsg("账号已存在");
			return;
		}
		renderSuccess();
	}

	public void delete() {
		Long id = getParaToLong("id");
		if (id == null) {
			renderError(500);
			return;
		}
		ZfAdmin info = ZfAdmin.dao.findById(id);
		if (info == null) {
			renderError(404);
			return;
		}
		renderFlag(info.delete());
	}

	public void logout() {
		AuthUtils.logout(this);
		redirect("/yq/admin/auth");
	}
}
